import type { CockpitSize } from './type'

/**
 * 获取值最小分子分母
 */
export function decimalToFraction(decimal: number) {
  const tolerance = 1.0e-6
  let h1 = 1
  let h2 = 0
  let k1 = 0
  let k2 = 1
  let b = decimal
  do {
    const a = Math.floor(b)
    let temp = h1
    h1 = a * h1 + h2
    h2 = temp
    temp = k1
    k1 = a * k1 + k2
    k2 = temp
    b = 1 / (b - a)
  } while (
    Math.abs(decimal - h1 / k1)
    > decimal * tolerance
  )

  return { numerator: h1, denominator: k1 }
}

/**
 * 大屏缩放
 * @param {number} size  [比例;默认为1920/1080]
 * @returns
 */
export function useCockpitScale(
  size: CockpitSize = {
    width: 1920,
    height: 1080,
  },
) {
  const [scale, setScale] = useState(0)

  const baseProportion = +(
    size.width / size.height
  ).toFixed(5)
  function handleResize() {
    const currentProportion = +(
      window.innerWidth / window.innerHeight
    ).toFixed(5)

    // ! 假定不会出现宽度、高度变大的情况
    if (currentProportion > baseProportion) {
      const m = +(
        (baseProportion * window.innerHeight)
        / size.width
      ).toFixed(5)
      //   宽
      setScale(m > 1 ? 1 : m)
    }
    else {
      const n = +(
        window.innerWidth
        / baseProportion
        / size.height
      ).toFixed(5)
      setScale(n > 1 ? 1 : n)
    }
  }

  window.addEventListener('resize', handleResize)
  onBeforeMount(() => {
    handleResize()
  })
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleResize)
  })
  return { scale }
}
